package com.wfg.spring.springRegistrar.FactoryBean;

import com.wfg.spring.springRegistrar.annotation.WfgMapper;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.HashSet;
import java.util.Set;

/**
 * @author: 王富贵
 * @description: 自定义注解注册器
 * @createTime: 2023/11/19 13:54
 */
public class WfgMapperRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        HashSet<String> annotationNames = new HashSet<>();
        annotationNames.add(WfgMapper.class.getName());
        WfgClassPathBeanDefinitionScanner wfgClassPathBeanDefinitionScanner = new WfgClassPathBeanDefinitionScanner(registry, annotationNames);

        // 方法1，重写ClassPathBeanDefinitionScanner的findCandidateComponents，替换扫描获得的Set<BeanDefinition>
        wfgClassPathBeanDefinitionScanner.scan("com.wfg.spring.springRegistrar.mapper");

        // 方法2. 调用findCandidateComponents方法获取Set<BeanDefinition>，手动通过registry注入
        Set<BeanDefinition> candidateComponents = wfgClassPathBeanDefinitionScanner.findCandidateComponents("com.wfg.spring.springRegistrar.mapper");
        for (BeanDefinition beanDefinition : candidateComponents) {
            // 被代理的类使用FactoryBean
            AbstractBeanDefinition proxyBeanDefinition = BeanDefinitionBuilder.genericBeanDefinition(SelectMapperFactoryBean.class)
                    // SelectMapperFactoryBean构造函数调用参数传入
                    .addConstructorArgValue(beanDefinition.getBeanClassName())
                    .getBeanDefinition();
            // 手动注册被代理过后的BeanDefinition
            // registry.registerBeanDefinition(beanDefinition.getBeanClassName(), proxyBeanDefinition);
        }
    }
}
